﻿using UnityEngine;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;

namespace ZXthex.Html
{
    public class RenderHtmlNode : ArrayTreeNodeProtected<RenderHtmlNode>
    {

        public ReadOnlyCollection<ReadOnlyHtmlAttribute> Attributes { get; private set; }

        public ReadOnlyHtmlAttribute GetAttribute(string attributeName)
        {
            for (int i = 0; i < Attributes.Count; i++)
            {
                if (Attributes[i].Name == attributeName)
                {
                    return Attributes[i];
                }
            }
            return null;
        }

        public string Name { get; private set; }
        public string InnerText { get; private set; }

        public string Id { get; private set; }

        private CSS_Declaration[] _declarations;
        public CSS_Declaration[] Declarations { get { return _declarations.Clone() as CSS_Declaration[]; } }

        private RenderHtmlNode()
        {
        }

        public static RenderHtmlNode From_DOM_and_CSSOM(ReadOnlyHtmlNode body, CSSStyleSheet css)
        {
            return Create_Internal(body, css, null);
        }

        static RenderHtmlNode Create_Internal(ReadOnlyHtmlNode r_node, CSSStyleSheet css, RenderHtmlNode parent)
        {
            RenderHtmlNode node = new RenderHtmlNode();
            node.Parent = parent;
            node.InnerText = r_node.InnerText;
            node.Name = r_node.Name;
            node.Id = r_node.Id;
            node.Attributes = r_node.Attributes;

            node._declarations = css.GetSuitableDeclarations(r_node);


            node.childs = new RenderHtmlNode[r_node.ChildCount];
            for (int i = 0; i < node.childs.Length; i++)
            {
                node.childs[i] = Create_Internal(r_node.GetChild(i), css, node);
            }
            return node;
        }

    }
}